package com.joysuch.wwyt.datadump.biz.convertor;

import cn.zlg.common.datadump.annotation.DataDumpField;
import cn.zlg.common.datadump.convertor.FieldValueConvert;
import com.alibaba.fastjson.JSON;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * @author zero
 * @since 2021/12/2 17:11
 */
@Component
public class ImportRiskDistrictResponsibleUser implements FieldValueConvert<String, String> {
    
    @Autowired
    private BaseUserDao baseUserDao;
    
    @Override
    public String convert(Object bean, String value, DataDumpField dataField) {
        if (StringUtils.isNotBlank(value)){
            String nameString = value.replaceAll(Constant.SPLIT_COMMA_FULL_WIDTH, Constant.SPLIT_COMMA);
            String[] names = nameString.split(Constant.SPLIT_COMMA);
            if (names.length == 0){
                throw new IllegalArgumentException("责任人填写格式错误请修改后重新导入");
            }
            if (!checkIsRepeat(names)){
                throw new IllegalArgumentException("责任人姓名重复请修改后重新导入");
            }
            List<Long> userIds = new ArrayList<>();
            for (String name : names){
                String nameTrim = name.trim();
                BaseUser baseUser = baseUserDao.findFirstByRealName(nameTrim);
                if (baseUser == null){
                    throw new IllegalArgumentException("责任人" + name + "不存在请修改后重新导入");
                }
                userIds.add(baseUser.getId());
            }
            return JSON.toJSONString(userIds);
        }
        return null;
    }

    /**
     *  检查是否是否有重复名字
     * @param names
     * @return
     */
    private boolean checkIsRepeat(String[] names){
        HashSet<String> checkSet = new HashSet<String>();
        Collections.addAll(checkSet, names);
        return checkSet.size() == names.length;
    }
}
